{% extends "base.html" %}

{% block title %}主面板 - Alist-Sync{% endblock %}

{% block page_title %}系统控制面板{% endblock %}

{% block content %}
<div class="row g-4">
    <!-- 统计卡片 -->
    <div class="col-md-3">
        <div class="card bg-primary bg-gradient text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h5 class="card-title">连接数</h5>
                        <h2 class="display-5 fw-bold" id="connection-count">0</h2>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-hdd-network fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-success bg-gradient text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h5 class="card-title">任务数</h5>
                        <h2 class="display-5 fw-bold" id="task-count">0</h2>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-list-task fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-info bg-gradient text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h5 class="card-title">活跃任务</h5>
                        <h2 class="display-5 fw-bold" id="active-task-count">0</h2>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-play-circle fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-warning bg-gradient text-dark">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h5 class="card-title">总同步文件</h5>
                        <h2 class="display-5 fw-bold" id="synced-files-count">0</h2>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-files fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 任务状态分布图表 -->
    <div class="col-md-6">
        <div class="card bg-dark-subtle">
            <div class="card-header bg-transparent">
                <h5 class="card-title mb-0">任务状态分布</h5>
            </div>
            <div class="card-body">
                <canvas id="task-status-chart" height="250"></canvas>
            </div>
        </div>
    </div>
    
    <!-- 连接类型统计图表 -->
    <div class="col-md-6">
        <div class="card bg-dark-subtle">
            <div class="card-header bg-transparent">
                <h5 class="card-title mb-0">连接类型分布</h5>
            </div>
            <div class="card-body">
                <canvas id="connection-type-chart" height="250"></canvas>
            </div>
        </div>
    </div>
    
    <!-- 任务执行时长统计图表 -->
    <div class="col-md-6">
        <div class="card bg-dark-subtle">
            <div class="card-header bg-transparent">
                <h5 class="card-title mb-0">任务执行时长统计</h5>
            </div>
            <div class="card-body">
                <canvas id="task-duration-chart" height="250"></canvas>
            </div>
        </div>
    </div>
    
    <!-- 任务执行成功率图表 -->
    <div class="col-md-6">
        <div class="card bg-dark-subtle">
            <div class="card-header bg-transparent">
                <h5 class="card-title mb-0">任务执行成功率</h5>
            </div>
            <div class="card-body">
                <canvas id="task-success-rate-chart" height="250"></canvas>
            </div>
        </div>
    </div>
    
    <!-- 近期任务表格 -->
    <div class="col-md-12">
        <div class="card bg-dark-subtle">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">近期任务执行</h5>
                <a href="{{ url_for('main.tasks') }}" class="btn btn-sm btn-primary">查看全部</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th>任务名称</th>
                                <th>同步类型</th>
                                <th>源路径</th>
                                <th>目标路径</th>
                                <th>状态</th>
                                <th>最后执行</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="recent-tasks">
                            <tr>
                                <td colspan="7" class="text-center">暂无任务数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 加载数据
        loadDashboardData();
        
        // 设置刷新间隔（从服务器端获取）
        var refreshInterval = {% if settings and settings.refresh_interval %}{{ settings.refresh_interval }}{% else %}60{% endif %};
        if (refreshInterval > 0) {
            setInterval(loadDashboardData, refreshInterval * 1000);
        }
    });
    
    // 加载仪表盘数据
    function loadDashboardData() {
        fetch('/api/dashboard/stats')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                updateDashboardStats(data.data);
                updateCharts(data.data);
                updateRecentTasks(data.data.recent_tasks);
            }
        })
        .catch(error => {
            console.error('获取仪表盘数据失败:', error);
        });
    }
    
    // 更新统计数据
    function updateDashboardStats(stats) {
        document.getElementById('connection-count').textContent = stats.connection_count || 0;
        document.getElementById('task-count').textContent = stats.task_count || 0;
        document.getElementById('active-task-count').textContent = stats.active_task_count || 0;
        document.getElementById('synced-files-count').textContent = stats.synced_files_count || 0;
    }
    
    // 更新图表
    function updateCharts(stats) {
        // 任务状态图表
        var taskStatusChartData = {
            labels: ['已完成', '进行中', '失败', '等待中'],
            datasets: [{
                data: [
                    stats.completed_task_count || 0, 
                    stats.running_task_count || 0, 
                    stats.failed_task_count || 0, 
                    stats.pending_task_count || 0
                ],
                backgroundColor: [
                    '#198754', // 绿色
                    '#0d6efd', // 蓝色
                    '#dc3545', // 红色
                    '#6c757d'  // 灰色
                ],
                borderWidth: 0
            }]
        };
        
        if (window.taskStatusChart) {
            window.taskStatusChart.data = taskStatusChartData;
            window.taskStatusChart.update();
        } else {
            var taskStatusCtx = document.getElementById('task-status-chart').getContext('2d');
            window.taskStatusChart = new Chart(taskStatusCtx, {
                type: 'doughnut',
                data: taskStatusChartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                color: '#212529'
                            }
                        }
                    }
                }
            });
        }
        
        // 连接类型分布图表
        var connectionTypeChartData = {
            labels: stats.connection_types || ['阿里云盘', '百度网盘', '夸克网盘', '天翼云盘', 'OneDrive'],
            datasets: [{
                data: stats.connection_type_counts || [2, 1, 2, 1, 1],
                backgroundColor: [
                    '#0d6efd', // 蓝色
                    '#dc3545', // 红色
                    '#ffc107', // 黄色
                    '#198754', // 绿色
                    '#6f42c1'  // 紫色
                ],
                borderWidth: 0
            }]
        };
        
        if (window.connectionTypeChart) {
            window.connectionTypeChart.data = connectionTypeChartData;
            window.connectionTypeChart.update();
        } else {
            var connectionTypeCtx = document.getElementById('connection-type-chart').getContext('2d');
            window.connectionTypeChart = new Chart(connectionTypeCtx, {
                type: 'pie',
                data: connectionTypeChartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                color: '#212529'
                            }
                        }
                    }
                }
            });
        }
        
        // 任务执行时长统计图表
        var taskDurationData = {
            labels: stats.task_duration_labels || ['小于1分钟', '1-5分钟', '5-15分钟', '15-30分钟', '30分钟以上'],
            datasets: [{
                label: '任务数量',
                data: stats.task_duration_counts || [8, 5, 3, 2, 1],
                backgroundColor: 'rgba(13, 110, 253, 0.7)',
                borderColor: '#0d6efd',
                borderWidth: 1
            }]
        };
        
        if (window.taskDurationChart) {
            window.taskDurationChart.data = taskDurationData;
            window.taskDurationChart.update();
        } else {
            var taskDurationCtx = document.getElementById('task-duration-chart').getContext('2d');
            window.taskDurationChart = new Chart(taskDurationCtx, {
                type: 'bar',
                data: taskDurationData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: '#212529'
                            }
                        },
                        x: {
                            ticks: {
                                color: '#212529'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }
        
        // 任务执行成功率图表
        var successRateData = {
            labels: stats.success_rate_labels || ['测试1', '测试2', '测试3', '测试4', '测试5'],
            datasets: [{
                label: '成功率 (%)',
                data: stats.success_rate_values || [80, 95, 60, 100, 85],
                backgroundColor: [
                    'rgba(25, 135, 84, 0.7)',
                    'rgba(25, 135, 84, 0.7)',
                    'rgba(220, 53, 69, 0.7)',
                    'rgba(25, 135, 84, 0.7)',
                    'rgba(25, 135, 84, 0.7)'
                ],
                borderColor: [
                    '#198754',
                    '#198754',
                    '#dc3545',
                    '#198754',
                    '#198754'
                ],
                borderWidth: 1
            }]
        };
        
        if (window.successRateChart) {
            window.successRateChart.data = successRateData;
            window.successRateChart.update();
        } else {
            var successRateCtx = document.getElementById('task-success-rate-chart').getContext('2d');
            window.successRateChart = new Chart(successRateCtx, {
                type: 'bar',
                data: successRateData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                color: '#212529'
                            }
                        },
                        x: {
                            ticks: {
                                color: '#212529'
                            }
                        }
                    }
                }
            });
        }
    }
    
    // 更新近期任务表格
    function updateRecentTasks(tasks) {
        var tableBody = document.getElementById('recent-tasks');
        if (!tasks || tasks.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无任务数据</td></tr>';
            return;
        }
        
        var html = '';
        tasks.forEach(function(task) {
            var statusClass = '';
            var statusText = '';
            
            switch(task.status) {
                case 'completed':
                    statusClass = 'success';
                    statusText = '已完成';
                    break;
                case 'running':
                    statusClass = 'primary';
                    statusText = '运行中';
                    break;
                case 'failed':
                    statusClass = 'danger';
                    statusText = '失败';
                    break;
                default:
                    statusClass = 'secondary';
                    statusText = '等待中';
            }
            
            html += `<tr>
                <td>${task.name}</td>
                <td>${task.sync_type === 'file_sync' ? '文件同步' : '其他'}</td>
                <td title="${task.source_path}">${task.source_path}</td>
                <td title="${task.target_path}">${task.target_path}</td>
                <td><span class="badge bg-${statusClass}">${statusText}</span></td>
                <td>${task.last_run || '-'}</td>
                <td>
                    <a href="/tasks?edit=${task.id}" class="btn btn-sm btn-outline-info me-1" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <button class="btn btn-sm btn-outline-success me-1" onclick="runTask(${task.id})" title="立即运行">
                        <i class="bi bi-play"></i>
                    </button>
                </td>
            </tr>`;
        });
        
        tableBody.innerHTML = html;
    }
    
    // 立即运行任务
    function runTask(taskId) {
        if (confirm('确定要立即运行这个任务吗？')) {
            fetch(`/api/tasks/${taskId}/run`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('任务已启动');
                    setTimeout(loadDashboardData, 1000);
                } else {
                    alert('启动任务失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('运行任务错误:', error);
                alert('运行任务失败: ' + error.message);
            });
        }
    }
</script>
{% endblock %} 